/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.imenu.web;

import com.imenu.ejb.ImenuCourseFacade;
import com.imenu.ejb.ImenuMenuFacade;
import com.imenu.entity.ImenuCourse;
import com.imenu.entity.ImenuMenu;
import com.imenu.web.image.ImageMode;
import com.imenu.web.image.ImageCropper;
import java.io.File;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import javax.ejb.EJB;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 *
 * @author yunzi
 */
@WebServlet(name = "ImageServlet", urlPatterns = {"/image"})
public class ImageServlet extends BaseServlet {

    public void form(HttpServletRequest request, HttpServletResponse response) throws Exception {
        forward(request, response, "/image/form.jsp");
    }
    @EJB
    ImenuCourseFacade courseFacade;

    /**
     * 图片上传后，依照下列命名规则处理：
     * 1. 原生图片存储在webapp/images/temp/下
     * 2. 封面图片，命名格式为 cover_menuId_landscape.xxx 及 cover_menuId_portrait.xxx
     * 3. 菜品图片，命名格式为 course_courseId_landscape.xxx 及 course_courseId_portrait.xxx
     */
    public void upload(HttpServletRequest request, HttpServletResponse response) throws Exception {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        boolean isMultipart = ServletFileUpload.isMultipartContent(httpRequest);
        System.out.println("ImageServlet.upload() isMultipart = " + isMultipart);
        // Create a factory for disk-based file items
        DiskFileItemFactory factory = new DiskFileItemFactory();

        // Set factory constraints
        int maxMemorySize = ImageConfig.IMAGE_MEMORY_MAX;
        int maxImageSize = ImageConfig.IMAGE_SIZE_MAX;
        factory.setSizeThreshold(maxMemorySize * 1024 * 1024);//max memory size in bytes
        factory.setRepository(new java.io.File(ImageConfig.IMAGE_TEMP_DIR));//temp directory 

        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);

        // Set overall request size constraint
        upload.setSizeMax(maxImageSize * 1024 * 1024);

        // Parse the request
        //the only FileItem
        FileItem fileItem = null;
        String menuId = null;//menu id
        String courseId = null;//course id
        String type = null;//"cover" or "course"
        String mode = null;//"landscape" or "portrait"
        List<FileItem> items = upload.parseRequest(httpRequest);
        Iterator<FileItem> iter = items.iterator();
        while (iter.hasNext()) {
            FileItem item = iter.next();

            if (item.isFormField()) {
                String name = item.getFieldName();
                String value = item.getString();
                System.out.println("LandscapeImageBean.upload() ............ name=" + name + " value=" + value);
                if ("menuId".equals(name)) {
                    menuId = value;
                } else if ("courseId".equals(name)) {
                    courseId = value;
                } else if ("type".equals(name)) {
                    type = value;
                } else if ("mode".equals(name)) {
                    mode = value;
                }
            } else {
                fileItem = item;
            }
        }
        if (fileItem == null || menuId == null || type == null || mode == null) {
            error(request, response, "参数错误，图片上传失败。");
        }
        String fieldName = fileItem.getFieldName();
        String fileName = fileItem.getName();
        String contentType = fileItem.getContentType();
        boolean isInMemory = fileItem.isInMemory();
        long sizeInBytes = fileItem.getSize();
        String extension = fileName.substring(fileName.lastIndexOf(".")).toUpperCase();
        System.out.println("LandscapeImageBean.upload() extension = "+extension);
        String path = ImageConfig.IMAGE_TEMP_DIR + "/" + type + "_" + ("course".equals(type) ? courseId : menuId) + "_" + mode + extension;


        System.out.println("LandscapeImageBean.upload() path = " + path);
        System.out.println("LandscapeImageBean.upload() fieldName = " + fieldName);
        System.out.println("LandscapeImageBean.upload() fileName = " + fileName);
        System.out.println("LandscapeImageBean.upload() contenType = " + contentType);
        System.out.println("LandscapeImageBean.upload() isInMemory = " + isInMemory);
        System.out.println("LandscapeImageBean.upload() sizeInBytes = " + sizeInBytes);
        File uploadedFile = new File(path);
        System.out.println("LandscapeImageBean.upload() uploadedFile = " + uploadedFile);
        System.out.println("LandscapeImageBean.upload() uploadedFile.getParentFile() = " + uploadedFile.getParentFile());
        if (!uploadedFile.exists()) {
            uploadedFile.getParentFile().mkdirs();
        }
        fileItem.write(uploadedFile);

        if ("course".equals(type)) {
            ImenuCourse course = courseFacade.find(Integer.valueOf(courseId));
            request.setAttribute("cropper", new ImageCropper(course.getMenu().getId() + "", course.getId() + "", type, mode, extension.toUpperCase()));
        } else {
            request.setAttribute("cropper", new ImageCropper(menuId, null, type, mode, extension.toUpperCase()));
        }
        try{
            ((ImageCropper)request.getAttribute("cropper")).getSize();
        }catch(Exception e){
            error(request, response, e.getMessage());
        }
        forward(request, response, "/image/crop.jsp");
    }

    public void crop(HttpServletRequest request, HttpServletResponse response) throws Exception {
        System.out.println("-----------------------------ImageServlet.crop() command = " + request.getParameter("command"));
        System.out.println("-----------------------------ImageServlet.crop() type = " + request.getParameter("type"));
        System.out.println("-----------------------------ImageServlet.crop() mode = " + request.getParameter("mode"));
        System.out.println("-----------------------------ImageServlet.crop() menuId = " + request.getParameter("menuId"));
        System.out.println("-----------------------------ImageServlet.crop() courseId = " + request.getParameter("courseId"));
        ImageCropper cropper = new ImageCropper();
        this.parseRequest(request, cropper);
        this.parseRequest(request, cropper.getCrop());
        System.out.println("-----------------------------ImageServlet.crop() cropper.getType() = " + cropper.getType());
        System.out.println("-----------------------------ImageServlet.crop() cropper.getMode() = " + cropper.getMode());
        System.out.println("-----------------------------ImageServlet.crop() cropper.getMenuId() = " + cropper.getMenuId());
        System.out.println("-----------------------------ImageServlet.crop() cropper.getCourseId() = " + cropper.getCourseId());
        System.out.println("-----------------------------ImageServlet.crop() cropper.getImageName() = " + cropper.getImageName());
        System.out.println("-----------------------------ImageServlet.crop() cropper.getCrop().getX() = " + cropper.getCrop().getX());
        System.out.println("-----------------------------ImageServlet.crop() cropper.getCrop().getY() = " + cropper.getCrop().getY());
        System.out.println("-----------------------------ImageServlet.crop() cropper.getCrop().getWidth() = " + cropper.getCrop().getWidth());
        System.out.println("-----------------------------ImageServlet.crop() cropper.getCrop().getHeight() = " + cropper.getCrop().getHeight());
        cropper.cut();
        if("course".equals(cropper.getType())){
            saveImageNameForCourse(cropper);
            forward(request, response, "/course?command=courseList&menuId="+cropper.getMenuId());
        }else{
            saveImageNameForMenu(cropper);
            forward(request, response, "/menu?command=menuList");
        }
        
    }

    @EJB ImenuMenuFacade menuFacade;
    private void saveImageNameForMenu(ImageCropper cropper) {
        Integer menuId = Integer.valueOf(cropper.getMenuId());
        ImenuMenu menu = this.menuFacade.find(menuId);
        if (ImageMode.Landscape.getValue().equals(cropper.getMode())) {
            menu.setImageLandscape(cropper.getImageName());
        } else {
            menu.setImagePortrait(cropper.getImageName());
        }
        menu.setUpdateTime(new java.util.Date());
        this.menuFacade.edit(menu);
    }

    private void saveImageNameForCourse(ImageCropper cropper) {
        Integer courseId = Integer.valueOf(cropper.getCourseId());
        ImenuCourse course = this.courseFacade.find(courseId);
        if (ImageMode.Landscape.getValue().equals(cropper.getMode())) {
            course.setLandscapeImage(cropper.getImageName());
        } else {
            course.setPortraitImage(cropper.getImageName());
        }
        course.setUpdateTime(new java.util.Date());
        course.getMenu().setUpdateTime(new java.util.Date());
        this.courseFacade.edit(course);
    }
}
